package com.black.auth.authority;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.black.auth.wechat.service.WxMiniAppService;
import com.black.common.constant.ShareConstant;
import com.black.common.feign.PlatformFeignClient;
import com.black.common.vo.ShareUserVo;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author linwenfeng
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WxUserDetailsServiceImpl implements UserDetailsService {

    private final PlatformFeignClient platformFeignClient;

    private final WxMiniAppService wxMiniAppService;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String jsCode) throws UsernameNotFoundException {
        WxMaJscode2SessionResult sessionInfo = wxMiniAppService.getCode2SessionInfo(jsCode);
        ShareUserVo loginUser;
        if (sessionInfo.getUnionid() != null) {
            loginUser = platformFeignClient.findUserByOtherId(sessionInfo.getUnionid(), ShareConstant.ThirdPartyId.UNION_ID).getResult();
        } else {
            loginUser = platformFeignClient.findUserByOtherId(sessionInfo.getOpenid(), ShareConstant.ThirdPartyId.OPEN_ID).getResult();
        }
        if (loginUser == null) {
            loginUser = getWechatUser(sessionInfo);
            loginUser = platformFeignClient.register(loginUser).getResult();
        }
        User user = new User(loginUser.getUsername(), loginUser.getPassword(),
                AuthorityUtils.NO_AUTHORITIES);
        return new OauthUser(user, loginUser);
    }

    private ShareUserVo getWechatUser(WxMaJscode2SessionResult sessionInfo) {
        ShareUserVo shareUserVo = new ShareUserVo();
        shareUserVo.setName("微信用户");
        shareUserVo.setUsername("微信用户");
        shareUserVo.setPassword("password");
        shareUserVo.setOpenId(sessionInfo.getOpenid());
        shareUserVo.setUnionId(sessionInfo.getUnionid());
        return shareUserVo;
    }
}
